<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use app\common\exception\ThrowException;
use Helper\ArrayHelper;
use app\common\model\base\BaseModel;
use app\common\token\token;
use app\common\traits\InstanceTrait;
use app\common\validate\AdminValidate;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Field;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;
use think\model\Collection;
use think\model\relation\BelongsTo;

class Admin extends BaseModel
{
    use InstanceTrait;

    public function __construct($data = [], Model $parent = NULL, $table = '')
    {
        parent::__construct($data, $parent, $table);
        $this->pk = 'admin_id';
        $this->initBaseField();
    }

    /**
     * 关联一对多-分类
     * @return \think\model\relation\HasMany
     */
    public function categorys()
    {
        return $this->hasMany(Category::class, 'creater_id', $this->pk)
                    ->where('status', '=', 1)
                    ->alias('category')
                    ->field(['category.*', 'category.category_id as id']);
    }

    /**
     * 关联一对多-获取用户所属所有用户组
     * @return \think\model\relation\HasMany
     */
    public function groups()
    {
        return $this->belongsToMany(AdminGroup::class, AdminGroupRelation::class, 'group_id', 'admin_id')
                    ->where('status', '=', 1)
                    ->cache(TRUE, 60)
                    ->alias('group')
                    ->field(['group.*', 'group.group_id as id'])
                    ->hidden($this->pivotHiddenField);
    }

    /**
     * 关联一对一-获取用户所属岗位
     * @return BelongsTo
     */
    public function structure(): BelongsTo
    {
        return $this->belongsTo(AdminStructure::class, 'structure_id', 'structure_id')
                    ->hidden($this->pivotHiddenField)
                    ->where('status', '=', 1);
    }

    /**
     * 关联一对一-获取用户部门
     * @return BelongsTo
     */
    public function post(): BelongsTo
    {
        return $this->belongsTo(AdminPost::class, 'post_id', 'post_id')
                    ->hidden($this->pivotHiddenField)
                    ->where('status', '=', 1);
    }

    public function fieldInfo()
    {

    }

    /**
     * @param array $param
     * @param string $alias
     * @return array|mixed
     */
    public function getBaseWhere($param = [], $alias = '')
    {
        if (!empty($alias)) {
            $alias = "{$alias}.";
        }
        $where = parent::getBaseWhere($param, $alias);
        if (!empty($param['keywords'])) {
            $where[] = [$alias . 'username|realname', 'like', '%' . $param['keywords'] . '%'];
        }
        if (!empty($param['id'])) {
            if (is_array($param['id'])) {
                $where[] = [$alias . $this->getPk(), 'in', $param['id']];
            } else {
                $where[] = [$alias . $this->getPk(), '=', $param['id']];
            }
        }
        if (!empty($param['group_id'])) {
            $group = AdminGroup::instance()->getByID($param['group_id']);
            $admin_id_arr = $group->admins->column('admin_id');
            $where[] = [$alias . 'admin_id', 'in', $admin_id_arr];
        }
        if (!empty($param['post_id'])) {
            $where[] = [$alias . 'post_id', 'in', $param['post_id']];
        }
        if (!empty($param['structure_id'])) {
            $where[] = [$alias . 'structure_id', 'in', $param['structure_id']];
        }
        return $where;
    }


    public function getByName($name)
    {
        $where = [
            ['username|phone', '=', $name],
        ];
        $ret = static::where($where)
                     ->field($this->baseField)
                     ->find();
        return $ret;
    }

    public function getAdminCount($param)
    {
        $Admin = static::instance();
        $where = $Admin->getBaseWhere($param);
        $dataCount = $Admin
            ->where($where)
            ->count();
        return $dataCount;
    }

    /**
     * 获取列表
     * @param $param
     * @return \think\Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DbException
     * @Field("admin_id,username,phone,password,remark,create_time,update_time,realname,structure_id,post_id,status,delete_time,creater_id,updater_id")
     * @Apidoc\Returned("post", type="object",ref="app\common\model\AdminGroup\getList",default="[]",desc="岗位")
     */
    public function getAdminList($param)
    {
        $Admin = static::instance();
        $where = $Admin->getBaseWhere($param);
        $param['page'] = !empty($param['page']) ? $param['page'] : 1;
        $param['limit'] = !empty($param['limit']) ? $param['limit'] : 15;
        $list = $Admin
            ->where($where)
            ->page($param['page'], $param['limit'])
            ->field($Admin->baseField)
            ->select();

        $list->hidden(['password', 'delete_time']);
        return $list;
    }

    /**
     * 根据ID获取值
     * @param string $id
     * @return BaseModel|null
     * @Field("admin_id,username,phone,password,remark,create_time,update_time,realname,structure_id,post_id,status,delete_time,creater_id,updater_id")
     * @Apidoc\Returned("dsf", type="object",default="{}", desc="详情")
     */
    public function getByID($id = '')
    {
        $data = $this->getAdminList(compact('id'));
        if (!empty($data) && FALSE == $data->isEmpty()) {
            return $data[0];
        }
        return $data;
    }


    /**
     * 通过jwt获取Admin
     * @param string $jwt [jwt]
     */
    public function getByToken($jwt)
    {
        Token::instance()->verifyToken($jwt);
        $user_info = Token::instance()->getUserInfo();
        return $user_info;
    }

    /**
     * 修改密码
     * @param array $param [description]
     */
    public function setInfo($auth_key, $old_pwd, $new_pwd)
    {
        $admin = AdminValidate::instance()->getTempAdmin();
        $uid = $admin[$this->pk];
        $this->where($this->pk, $uid)->setField('password', encrypt_password($new_pwd));
        return $auth_key;//把auth_key传回给前端
    }

    /**
     * 获取admin的rule数组
     * @param $admin_id
     * @return \think\model\Collection|null
     * @throws DbException
     */
    public function getRuleList($admin_info)
    {
        $rule_arr = new Collection();
        if (!empty($admin_info)) {
            $groups = $admin_info->groups;
            foreach ($groups as $k => $v) {
                $rule_arr = $v['rules']->merge($rule_arr);
            }
        }
        return \think\model\Collection::make($rule_arr);
    }

    /**
     * 获取菜单和权限
     * @param $admin_info
     * @return null | Array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getMenuList($admin_info)
    {
        $ret = [];
        if (!empty($admin_info)) {
            $admin_info->groups->load('menus');
            $menusList = ArrayHelper::arrayColumnMerge($admin_info['groups'], 'menus');
            $menusList = array_unique($menusList);
            $menusList = Collection::make($menusList)->toArray();
            //处理菜单成树状
            $ret['menusList'] =
                ArrayHelper::arrayToTree($menusList, 'menu_id', 'pid', 'child', 0, TRUE, array('pid'));
        }
        return $ret;
    }
}
